import React,{Component} from 'react'
import { NavBar, Icon } from 'antd-mobile';
import {Link} from 'react-router-dom'
import './index.css'
import {getChapter,getSource} from '../../api'

class Chapter extends Component{
    constructor(props) {
        super(props)
        this.state = {          
            chapterList: [],
            source: [],
            id: props.location.state.id          
        }      
    }
    // 返回
    go() {
        this.props.history.go(-1)
    } 

    componentDidMount(){
        getSource(this.state.id)
        .then( res=>{
            this.setState(()=>({
                source: res.data[0]            
            }))  

            getChapter(this.state.source._id)  
            .then(result=>{
                this.setState( ()=>({
                   chapterList: result.data.chapters
                }))                
            })  

        })         
    }
  
    render(){
        return(
            <div className='app-chapter-box'>
                <header>
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" onClick={this.go.bind(this)} />}
                        rightContent={[
                            <Icon key="0" type="home" style={{ marginRight: '16px' }} />
                        ]}
                    ><span>
                        {this.state.source.name?this.state.source.name:''}
                    </span></NavBar>
                </header>         
                <h4>目录<span>共{this.state.chapterList?this.state.chapterList.length:''}章</span></h4>
                <ul>
                 { this.state.chapterList?
                    this.state.chapterList.map( (item,index)=>{
                        return (                      
                            <li key={index}>
                                <Link to={ {pathname:'/paper',state:{text: item.link}} }>{item.title}</Link>
                            </li>        
                        )
                    })                       
                    :''
                    }                             
                </ul>                
            </div>
        )
    }
}
export default  Chapter